import React, {
  Component,
  useState,
  useEffect
} from "react";
import {
  ScrollView,
  Text,
  TouchableOpacity,
} from "react-native";
import Content from "../../components/content/content";
import styles from "./detail-sheet";
import TaskDetailsComponent from "../../components/task-details/task-details";
import * as api from "../../api";

export default function Detail(props) {
  const [data, setData] = useState([]);
  const [showDetails, setShowDetails] = useState(false);
  const np = props.navigation.state.params;

  const getTaskDetails = () => {
    if (np.id) {
      global.showLoading();
      api.getTaskDetails({
        id: np.id,
      }).then(res => {
        setData(res);
        setShowDetails(true);
      }).catch(rej => {
        global.showToast(rej);
      }).finally(() => {
        global.closeLoading();
      });
    } else {
      global.showToast('参数错误');
    }
  }
  useEffect(() => {
    getTaskDetails();
  }, [])

  const applyTask = () => {
    if (np.id) {
      global.showLoading();
      api.applyTask({
        "task_id": np.id,
      }).then(res => {
        global.showToast('报名成功');
        props.navigation.replace("AchieveTask", {
          id: np.id,
          applicant_id: res.applicant_id,
        });
        global.onfire.fire('applyTask');
      }).catch(rej => {
        global.showToast(rej);
      }).finally(() => {
        global.closeLoading();
      });
    } else {
      global.showToast('参数错误');
    }
  }

  renderData = () => {
    return (
      showDetails ? <TaskDetailsComponent {...data} /> : null
    );
  }

  return (
    <Content>
      <ScrollView alwaysBounceVertical={false}>
        {renderData()}
        <TouchableOpacity style={styles.buttonContent} onPress={applyTask}>
          <Text style={styles.button}>接单</Text>
        </TouchableOpacity>
      </ScrollView>
    </Content>
  )
}